/**
 * 主服务 全局事件监听
 */
import { getStore } from '@/utils/otherUtil';
import { getMasterCommonPkg } from '@/utils/masterData';
const { getState, ep } = getMasterCommonPkg();

class MasterEvent {
  // 绑定事件
  static bindEvent() {
    ep.on('masterStateChange', masterStateChange);
  }

  // 取消绑定事件
  static removeListener() {
    ep.removeListener('masterStateChange', masterStateChange); //取消事件监听
  }

  // 同步全局状态 (项目挂载时候调用)
  static getMasterState() {
    var { user, masterGlobal } = getState();
    var t = setTimeout(() => {
      clearTimeout(t);
      var store = getStore();
      store.dispatch({ type: `user/setState`, payload: user });
      store.dispatch({ type: `masterGlobal/setState`, payload: masterGlobal });
    }, 50);
  }
}

// 同步主服务数据 （主服务发生变动回掉函数）
function masterStateChange(msg) {
  var store = getStore();
  store.dispatch({
    type: `${msg.name}/setState`,
    payload: msg.value,
  });
}

export default MasterEvent;
